"""
Case Type   : 资源池化系统视图
Case Name   : 结合gs_collector工具,查看系统视图收集信息
Create At   : 2025/2
Owner       : haomeng
Description :
    1、配置config1.json文件，收集项指定对应视图
    2、执行gs_collector操作收集
    3、解压收集信息，查看是否存在对应的内存视图相关信息
    4、配置config2.json文件，收集项指定对应视图，收集次数为多次
    5、执行gs_collector操作收集
    6、解压收集信息，查看是否存在多个对应的内存视图相关信息
    7、恢复初始环境，清理环境
Expect      :
    1、配置文件定义成功
    2、收集操作执行成功
    3、收集文件内存在DMSDrcontext & DMSMemContext字段信息
    4、配置文件定义成功
    5、收集操作执行成功
    6、收集文件内存在DMSDrcontext & DMSMemContext字段信息，且文件存在多个
    7、环境恢复成功
History     :
"""

import os
import stat
import json
import unittest
from datetime import datetime, timedelta

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class ShareStorageSystemView(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_sh = CommonSH('Standby1DbUser')
        self.user_node = Node('PrimaryDbUser')
        self.root_node = Node('PrimaryRoot')
        self.constant = Constant()

        self.config1 = os.path.join(macro.DB_BACKUP_PATH, 'config1.json')
        self.config2 = os.path.join(macro.DB_BACKUP_PATH, 'config2.json')

    def test_ss_system_view(self):
        text = '-----step1:配置config1.json文件，收集项指定对应视图;  expect:配置文件定义成功-----'
        self.log.info(text)

        data = {"Collect":
                    [{"TypeName": "Database",
                      "Content": "gs_thread_memory_context,pg_total_memory_detail,gs_shared_memory_detail,gs_total_memory_detail",
                      "Interval": "0", "Count": "1", "FileNumber": "0"}]}
        self.log.info(json.dumps(data))

        with open(self.config1, 'w') as f:
            json.dump(data, f)

        chmod = os.chmod(self.config1, stat.S_IRWXO)
        self.log.info(chmod)

        check = self.user_node.sh(f'cat {self.config1}').result()
        self.log.info(check)
        self.assertIn('gs_thread_memory_context', check, '执行失败:' + text)

        text = '-----step2:执行gs_collector操作收集  expect:收集操作执行成功-----'
        self.log.info(text)

        time1 = datetime.now()
        time2 = time1 + timedelta(hours=1)
        hostname = self.user_node.sh('hostname').result()
        self.log.info(hostname)

        start_time = time1.strftime('%Y%m%d %H:%M')
        self.log.info(start_time)
        end_time = time2.strftime('%Y%m%d %H:%M')
        self.log.info(end_time)

        collect_cmd = f'source {macro.DB_ENV_PATH};' \
                      f'gs_collector --begin-time="{start_time}" --end-time="{end_time}" -h {hostname} -C {self.config1}'
        self.log.info(collect_cmd)
        collect_res = self.user_node.sh(collect_cmd).result()
        self.log.info(collect_res)
        self.assertIn('Successfully collected files', collect_res, '执行失败:' + text)

        text = '-----step3:解压收集信息，查看是否存在对应的内存视图相关信息   ' \
               'expect:收集文件内存在DMSDrcContext & DMSMemContext字段信息-----'
        self.log.info(text)

        file_name = collect_res.splitlines()[-1].split('/')[-1].split('.')[0]
        self.log.info(file_name)

        cat_collect = f'cd {macro.PG_LOG_PATH}/../; ' \
                      f'tar -zxvf *.tar.gz; ' \
                      f'cd {file_name}; ' \
                      f'tar -zxvf *.tar.gz; ' \
                      f'cd {hostname};' \
                      f'cat catalogfiles/dn_6001_gs_shared_memory_detail* | grep DMSDrcContext'
        self.log.info(cat_collect)

        tar_res = self.user_node.sh(cat_collect).result()
        self.log.info(tar_res)
        self.assertIn('DMSDrcContext', tar_res, '执行失败:' + text)

        text = '-----step4:配置config2.json文件，收集项指定对应视图，收集次数为多次  expect:配置文件定义成功-----'
        self.log.info(text)

        data = {"Collect":
                    [{"TypeName": "Database",
                      "Content": "gs_thread_memory_context,pg_total_memory_detail,gs_shared_memory_detail,gs_total_memory_detail",
                      "Interval": "3", "Count": "3", "FileNumber": "0"}]}
        self.log.info(json.dumps(data))

        with open(self.config2, 'w') as f:
            json.dump(data, f)

        chmod = os.chmod(self.config2, stat.S_IRWXO)
        self.log.info(chmod)

        check = self.user_node.sh(f'cat {self.config2}').result()
        self.log.info(check)
        self.assertIn('gs_thread_memory_context', check, '执行失败:' + text)

        text = '-----step5:执行gs_collector操作收集  expect:收集操作执行成功-----'
        self.log.info(text)

        self.log.info('---删除已有收集文件---')
        del_cmd = f'cd {macro.PG_LOG_PATH}/../;' \
                  f'rm -rf collector_*'
        self.log.info(del_cmd)
        del_res = self.user_node.sh(del_cmd).result()
        self.log.info(del_res)

        collect_cmd = f'source {macro.DB_ENV_PATH};' \
                      f'gs_collector --begin-time="{start_time}" --end-time="{end_time}" -h {hostname} -C {self.config2}'
        self.log.info(collect_cmd)
        collect_res = self.user_node.sh(collect_cmd).result()
        self.log.info(collect_res)
        self.assertIn('Successfully collected files', collect_res, '执行失败:' + text)

        text = '-----step6:解压收集信息，查看是否存在多个对应的内存视图相关信息  ' \
               'expect:收集文件内存在DMSDrcontext & DMSMemContext字段信息，且文件存在多个-----'
        self.log.info(text)

        file_name = collect_res.splitlines()[-1].split('/')[-1].split('.')[0]
        self.log.info(file_name)

        cat_collect = f'cd {macro.PG_LOG_PATH}; ' \
                      f'tar -zxvf *.tar.gz; ' \
                      f'cd {file_name}; ' \
                      f'tar -zxvf *.tar.gz; ' \
                      f'cd {hostname}/catalogfiles/; ' \
                      f'cat dn_6001_gs_shared_memory_detail* | grep DMSDrcContext;' \
                      f'ls *gs_shared_memory_detail* | wc -l'
        self.log.info(cat_collect)

        tar_res = self.user_node.sh(cat_collect).result()
        self.log.info(tar_res)
        self.assertIn('DMSDrcContext', tar_res, '执行失败:' + text)
        self.assertEqual('3', tar_res.splitlines()[-1].strip(), '执行失败:' + text)

    def tearDown(self):
        text = '-----step7:恢复初始环境  expect:恢复成功-----'
        self.log.info(text)

        del_cmd = f'cd {macro.PG_LOG_PATH}/../;' \
                  f'rm -rf collector_*; ' \
                  f'ls collector*'
        self.log.info(del_cmd)
        del_res = self.user_node.sh(del_cmd).result()
        self.log.info(del_res)
        self.assertIn('No such file or directory', del_res, '执行失败:' + text)
        self.log.info(f'----{os.path.basename(__file__)} end----')
